//
//  DSPDSPUserCountViewModel.swift
//  SWweibo
//
//  Created by 杜守鹏 on 15/12/30.
//  Copyright © 2015年 杜守鹏. All rights reserved.
//

import UIKit

private var  accountPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true ).last! as NSString).stringByAppendingPathComponent("account.archive")

class DSPDSPUserCountViewModel: NSObject {
    
    static let sharedUserCountViewModel:DSPDSPUserCountViewModel = DSPDSPUserCountViewModel()
    
    //MARK:存账号信息
    class func saveAccount(account:DSPUserCount){
        account.buildTime = NSDate()
        NSKeyedArchiver.archiveRootObject(account, toFile: accountPath)
    }
    
    //MARK:取帐号信息，并判断时间是否过期
    class func account()->(DSPUserCount?){
  
//        let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as! DSPUserCount
   
        guard let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as?DSPUserCount else{
            
            return nil 
            
        }
        
//        print(account.screen_name)
//        print(account.avatar_large)
//        print(account.uid)
//        let expires_in = (account.expires_in! as NSString).doubleValue
        let expires_in = account.expires_in
        //MARK:过期时间
        let expiresTime = account.buildTime?.dateByAddingTimeInterval(expires_in)
        
        let now = NSDate()
 
        if expiresTime?.compare(now) != .OrderedDescending{
            
        return nil
            
        }
           return account
    }
    
    //MARK:获取accessTocken
    func acessTokenFromCode(code:String,completed:(isSucceed:Bool)->()){
        
        DSPNetTools.sharedTools.loadAccessTocken(code) { (response, error) -> () in
            if error != nil {
                print(error)
                completed(isSucceed: false)
                return
            }
            let account = DSPUserCount.init(dict: (response as! [String:AnyObject]))
            //            DSPDSPUserCountViewModel.saveAccount(account)
            self.loadUserImage(account,complete: completed)
        }
         }
//MARK:获取个人信息
    func loadUserImage(account:DSPUserCount,complete:(isSuccess:Bool)->()){
        
        DSPNetTools.sharedTools.loadUserImage(account.access_token!, uid: account.uid!) { (response, error) -> () in
            if error != nil {
                print(error )
                complete(isSuccess: false )
                return
            }
            
            guard let dict = response as? [String:AnyObject] else{
                complete(isSuccess: false )
                return
            }
            account.avatar_large = dict["avatar_large"] as? String
            account.screen_name = dict["screen_name"] as? String
            //            print("--\(account.avatar_large)")
            //            print("--\(account.screen_name)")
            DSPDSPUserCountViewModel.saveAccount(account)
            complete(isSuccess: true )

        }
}
}
